<template>
  <div>
    <!-- 用户导入对话框 -->
    <el-dialog class="dia-style" title="导入" width="600px" :visible.sync="upload.open" :close-on-click-modal="false" @close="cancel">
      <el-upload
        v-if="showFirst"
        ref="upload"
        :limit="1"
        accept=".zip"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-change="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        multiple
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div><span>支持扩展名：.zip</span></div>
      </el-upload>
      <div v-else>
        <HkTable
          ref="tableRef"
          :table-data="tableData"
          :table-columns="tableList"
          :selection="true"
          :show-index="true"
          :operate="true"
          :show-pag="false"
          @handleSelectionChange="handleSelectionChange"
        >
          <template #operate="scope">
            <span v-if="!scope.row.sel">--</span>
            <span v-else-if="scope.row.sel && scope.row.upType == 1">覆盖</span>
            <span v-else-if="scope.row.sel && scope.row.upType == 0">新增</span>
          </template>
          <template #upType="scope">
            <span v-if="scope.row.upType == 1"> 存在同名文件 </span>
            <span v-else>新增文件</span>
          </template>
        </HkTable>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="showFirst" type="primary" @click="submitFileForm">上 传</el-button>
        <el-button v-else type="primary" @click="saveFileForm">保 存</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import axios from 'axios'
import HkTable from '@/components/Hk-Table/index.vue'
import { importRuleList } from '@/api/icp/labelClassDisplay'
export default {
  components: { HkTable },
  data() {
    return {
      ids: [],
      total: 0,
      tableData: [],
      tableList: [
        { label: '标签名称', param: 'name' },
        { label: '文件状态', param: 'upType', type: 'slot' }
      ],
      showFirst: true,
      fileList: [],
      importZip: undefined,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: true,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: window.baseUrl.icp + '/rule/importFile'
      },
      queryParams: {
        size: 10,
        current: 1
      }
    }
  },
  methods: {
    // 点击换页
    getList(val) {
      this.queryParams = val
    },
    // 选择框选中
    handleSelectionChange(data) {
      this.ids = data.map((item) => item.id)
      this.tableData.forEach((item) => {
        if (this.ids.includes(item.id)) {
          item.sel = true
        } else {
          item.sel = false
        }
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(file, fileList) {
      this.fileList.push({
        importZip: fileList[0].raw
      })
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
      )
    },
    // 提交上传文件
    submitFileForm() {
      const form = new FormData()
      this.fileList.forEach((item, key) => {
        form.append('file', item.importZip)
      })
      axios({
        method: 'post',
        url: window.baseUrl.icp + '/rule/uploadFile',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        transformRequest: [
          function() {
            return form
          }
        ],
        params: form
      }).then((res) => {
        console.log(res)
        const data = res.data.data
        if (data && data.length > 0) {
          this.showFirst = false
          this.total = data.length
          this.tableData = data
        } else {
          this.$message.warning(res.data.msg)
        }
      })
    },
    // 保存表单
    saveFileForm() {
      let ruleVos
      // eslint-disable-next-line prefer-const
      ruleVos = this.tableData.filter((item) => {
        return item.sel
      })
      if (ruleVos.length === 0) {
        this.$message.warning('未选择任何选项')
      } else {
        importRuleList(JSON.stringify(ruleVos)).then((res) => {
          this.$message.success('导入成功')
          this.cancel()
          this.upload.open = false
          this.$emit('submit')
        })
      }
    },
    //   取消
    cancel() {
      this.showFirst = true
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-upload-dragger {
    width: 550px;
  }
  .el-dialog__body {
    //max-height: 400px;
    display: flex;
    flex-direction: column;
    text-align: center;
    div {
      .targetTable {
        margin-top: -20px;
        margin-bottom: -20px;
      }
    }
  }
}
</style>
